"""
Flask应用工厂
"""
from flask import Flask
from app.extensions import db, login_manager
from app.config import Config


def create_app(config_class=Config):
    """创建Flask应用实例"""
    import os
    # 指定静态文件和模板文件的路径
    template_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))
    static_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'static'))
    
    app = Flask(__name__, 
                static_folder=static_dir,
                template_folder=template_dir)
    app.config.from_object(config_class)
    
    # 导入所有模型以确保它们被注册
    from app.models.user import User
    from app.models.customer import Customer
    from app.models.staff import Staff, StaffProject
    from app.models.associations import CustomerStaff
    from app.models.negotiation import Negotiation, UploadException
    from app.models.attendance import Attendance
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    
    # 配置user_loader
    @login_manager.user_loader
    def load_user(user_id):
        from app.models.user import User
        return User.query.get(int(user_id))
    
    # 注册蓝图
    from app.routes.auth import auth_bp
    from app.routes.main import main_bp
    from app.routes.customer import customer_bp
    from app.routes.staff import staff_bp
    from app.routes.negotiation import negotiation_bp
    from app.routes.statistics import statistics_bp
    from app.routes.reports import reports_bp
    from app.routes.attendance import attendance_bp
    
    app.register_blueprint(auth_bp)
    app.register_blueprint(main_bp)
    app.register_blueprint(customer_bp)
    app.register_blueprint(staff_bp)
    app.register_blueprint(negotiation_bp)
    app.register_blueprint(statistics_bp)
    app.register_blueprint(reports_bp)
    app.register_blueprint(attendance_bp)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
        
        # 创建默认管理员用户
        from app.models.user import User
        admin = User.query.filter_by(username='admin').first()
        if not admin:
            admin = User(username='admin')
            admin.set_password('admin123')
            db.session.add(admin)
            db.session.commit()
    
    return app
